/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.geekidea.springbootplus.system.controller;

import io.geekidea.springbootplus.framework.common.api.ApiCode;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.shiro.util.JwtTokenUtil;
import io.geekidea.springbootplus.framework.shiro.vo.LoginSysUserVo;
import io.geekidea.springbootplus.system.service.SysPermissionService;
import io.geekidea.springbootplus.system.vo.SysPermissionTreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 菜单 控制器
 *
 * @author yangyi
 * @date 2020-06-23
 * @since 1.3.0.RELEASE
 **/
@Slf4j
@RestController
@RequestMapping("/menu")
@Api(value = "菜单控制器 API", tags = {"菜单管理"})
public class MenuController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysPermissionService sysPermissionService;

    /**
     * 根据用户id获取菜单树形列表
     */
    @GetMapping("/getMenuList")
    @ApiOperation(value = "根据用户id获取菜单树形列表", response = SysPermissionTreeVo.class)
    public ApiResult<SysPermissionTreeVo> getMenuList() throws Exception {
        String token =  JwtTokenUtil.getToken();
        String tokenSha256 = DigestUtils.sha256Hex(token);
        LoginSysUserVo loginSysUserVo = (LoginSysUserVo) redisTemplate.opsForValue().get(tokenSha256);
        if (loginSysUserVo == null) {
            return ApiResult.fail(ApiCode.UNAUTHORIZED);
        }
        // 根据用户id获取菜单列表
        List<SysPermissionTreeVo> list = sysPermissionService.getMenuTreeByUserId(loginSysUserVo.getId());
        //List<SysPermissionTreeVo> list = sysPermissionService.getMenuTreeByUserId(1L);
        return ApiResult.ok(list);

    }

}
